package com.ecjtu.stadiumre_servations.service.impl;

import com.ecjtu.stadiumre_servations.config.RabbitMQConfig;
import com.ecjtu.stadiumre_servations.entity.domain.Booking;
import com.ecjtu.stadiumre_servations.service.BookingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class PaymentTimeoutConsumer {
    private static final Logger logger = LoggerFactory.getLogger(PaymentTimeoutConsumer.class);

    @Autowired
    private BookingService bookingService;

    /**
     * 监听支付超时队列，处理超时未支付的预约
     * @param timeoutMessage 超时消息，包含预约ID
     */
    @RabbitListener(queues = RabbitMQConfig.PAYMENT_TIMEOUT_QUEUE_NAME)
    public void handlePaymentTimeout(Map<String, String> timeoutMessage) {
        String bookingId = timeoutMessage.get("bookingId"); // 获取预约ID
        try {
            Booking booking = bookingService.getById(bookingId);
            // 检查预约是否存在且仍处于待支付状态
            if (booking != null && "待支付".equals(booking.getBookingStatus())) {
                // 修改预约状态为已取消
                booking.setBookingStatus("已取消");
                bookingService.updateById(booking);
                logger.info("预约ID: {} 因支付超时已取消", bookingId);
            }
        } catch (Exception e) {
            logger.error("处理支付超时预约时出现异常，预约ID: {}", bookingId, e);
        }
    }
}